from appium import webdriver
from selenium.webdriver.common.by import By as AppiumBy
import time
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

def initialize_driver():
    desired_caps = {
        "platformName": "Android",        # 操作系统
        "platformVersion": "7.1.2",          # 安卓版本
        "deviceName": "127.0.0.1:62001",      # 设备名称
        "appPackage": "com.suntek.smartlife",   # 目标App包名
        "appActivity": "com.smart.ThingSplashActivity",  # 启动Activity
        "noReset": False,                  # 重置App状态
        "automationName": "UiAutomator2", # 自动化引擎
        "newCommandTimeout": 1200
    }
    driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
    driver.implicitly_wait(10)
    return driver

def login(driver):
    try:
        logging.info("开始登录流程")
        agree_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/positiveButton")
        agree_btn.click()
        time.sleep(3)
        logging.info("点击继续使用按钮")
        ctu_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
        ctu_btn.click()
        time.sleep(3)
        
        logging.info("点击确认按钮")
        login_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/btn_login")
        login_btn.click()
        time.sleep(3)
        
        logging.info("输入用户名")
        input_name = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/et_text")
        input_name.send_keys("17279412354")
        time.sleep(3)
        
        logging.info("输入密码")
        password_input = driver.find_element(AppiumBy.XPATH, "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.ScrollView/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout[2]/android.view.ViewGroup/android.widget.EditText")
        password_input.send_keys("cg123123")
        
        logging.info("同意协议")
        agr_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/cb_agreement")
        agr_btn.click()
        
        logging.info("点击登录按钮")
        dl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_text")
        dl_btn.click()
        time.sleep(5)

        logging.info("点击进入按钮")
        # jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/deviceName")
        jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorX")
        jl_btn.click()
       
        
        
        logging.info("关闭位置权限")
        ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
        ys_btn.click()
        time.sleep(20)
        
    except Exception as e:
        logging.error(f"执行过程中出现异常: {str(e)}")
        driver.quit()

def upgrade(driver):
    try:
        if driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm"):
            logging.info("开始升级流程")
            for i in range(100):
                logging.info(f"开始第 {i+1} 次升级")
                upgrate_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
                upgrate_btn.click()
                time.sleep(2)
                
                new_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_operation")
                new_btn.click()
                
                staup_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
                staup_btn.click()
                
                logging.info("升级中")
                time.sleep(700)
                logging.info("升级完成")
                time.sleep(3)
                lkown_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv")
                lkown_btn.click()
                time.sleep(3)
                 #返回
                back_btn = driver.find_element(AppiumBy.XPATH, "	//android.view.ViewGroup[@content-desc='TopBar_Btn_Back']/android.view.View")      
                back_btn.click()
                time.sleep(2)

                logging.info("点击进入按钮")
                jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorY")
                jl_btn.click()
                driver.implicitly_wait(10)
                
                logging.info("关闭位置权限")
                ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
                ys_btn.click()
                time.sleep(20)
        else:
            logging.info("进入设备升级")
            bl_btn = driver.find_element(AppiumBy.ID, "//android.view.ViewGroup[@content-desc='TopBar_Btn_RightItem']/android.view.View")
            bl_btn.click()
            sbota_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/fl_item")
            sbota_btn.click()
            new_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_operation")
            new_btn.click()
            staup_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_confirm")
            staup_btn.click()
            # back_btn

            # for _ in range(60):  # 每次等待10秒，总共等待900秒（15分钟）
            #     time.sleep(15)
            #     logging.info("升级中...")
            time.sleep(700)
            logging.info("升级完成")
            time.sleep(3)
            lkown_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv")
            lkown_btn.click()
            time.sleep(3)
            #返回
            back_btn = driver.find_element(AppiumBy.XPATH, "	//android.view.ViewGroup[@content-desc='TopBar_Btn_Back']/android.view.View")      
            back_btn.click()
            time.sleep(2)

            logging.info("点击进入按钮")
            jl_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/anchorY")
            jl_btn.click()
            driver.implicitly_wait(10)
            
            logging.info("关闭位置权限")
            ys_btn = driver.find_element(AppiumBy.ID, "com.suntek.smartlife:id/tv_close")
            ys_btn.click()
            time.sleep(20)
            
    except Exception as e:
        logging.error(f"执行过程中出现异常: {str(e)}")
    finally:
        driver.quit()
        driver.close_app()
        logging.info("重新初始化驱动并重试")
        driver = initialize_driver()
        login(driver)
        upgrade(driver)
        

if __name__ == "__main__":
    driver = initialize_driver()
    login(driver)
    upgrade(driver)